package com.escope.casemanager.service.impl;

import com.escope.casemanager.dao.CaseExampleDao;
import com.escope.casemanager.model.*;
import com.escope.casemanager.service.CaseExampleService;
import com.escope.casemanager.service.SysMessageService;
import com.escope.casemanager.uti.DateUtil;
import com.escope.casemanager.uti.JpaUtil;
import com.escope.casemanager.uti.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.*;
import java.util.*;

/**
 * Administrator
 * 2024/3/15
 */
@Transactional(rollbackFor = Exception.class)
@Service("caseExampleService")
public class CaseExampleServiceImpl implements CaseExampleService {
    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private CaseExampleDao caseExampleDao;
    @Autowired
    private SysMessageService sysMessageService;

    @Override
    @Transactional
    public HttpResult saveOrUpdate(CaseExample example) {
        SysUserCacheInfo cacheInfo = redisUtil.getCacheUser();
        CaseExample db_example = null;
        if(example.getId() == null){
            db_example = new CaseExample();
            db_example.setCreateTime(new Date());
            db_example.setCreateUser(cacheInfo.getUser().getId());
            SysMessage message = new SysMessage();
            message.setType("2");
            message.setMsg(example.getName()+" 案例已发布成功, 可立即体验！");
            sysMessageService.saveSysMessage(message);
        }else{
            db_example = caseExampleDao.findById(example.getId()).get();
            db_example.setUpdateTime(new Date());
            db_example.setUpdateUser(cacheInfo.getUser().getId());
            if(DateUtil.getCurTime().getTime().compareTo(db_example.getMapEndTime()) <= 0){
                db_example.setStatus("0");
            }
        }
        JpaUtil.copyNotNullProperties(example, db_example);
        caseExampleDao.save(db_example);

        return HttpResult.ok();
    }

    @Override
    public void update(CaseExample example) {
        caseExampleDao.save(example);
    }

    @Override
    public HttpResult findById(Long id) {
        return HttpResult.ok(caseExampleDao.findByIdAndBdelete(id, "0"));
    }

    @Override
    public List<CaseExample> findExpire() {
        Calendar cal = DateUtil.getCurTime();
        cal.add(Calendar.DAY_OF_MONTH, 5);
        return caseExampleDao.findExpire(cal.getTime());
    }

    @Override
    public HttpResult delete(Long id) {
        Optional<CaseExample> example = caseExampleDao.findById(id);
        example.get().setBdelete("1");
        caseExampleDao.save(example.get());
        return HttpResult.ok();
    }

    @Override
    public HttpResult findByPage(PageModel page, Map<String, Object> map) {
        //页码：前端从1开始，jpa从0开始，做个转换
        Pageable pageable = PageRequest.of(page.getPageNum() - 1, page.getPageSize(), Sort.by(Sort.Direction.DESC, "id"));
        Page<CaseExample> cePage = caseExampleDao.findAll(new Specification<CaseExample>() {
            @Override
            public Predicate toPredicate(Root<CaseExample> root, CriteriaQuery<?> query, CriteriaBuilder builder) {

                List<Predicate> preds = new ArrayList<>();

                String typeCode = (String) map.get("typeCode");
                if (!StringUtils.isEmpty(typeCode) && !"-1".equals(typeCode)) {
                    Predicate p = builder.equal(root.get("typeCode").as(String.class), typeCode);
                    preds.add(p);
                }

                String industryCode = (String) map.get("industryCode");
                if (!StringUtils.isEmpty(industryCode) && !"-1".equals(industryCode)) {
                    Predicate p = builder.equal(root.get("industryCode").as(String.class), industryCode);
                    preds.add(p);
                }

                String name = (String) map.get("name");
                if (!StringUtils.isEmpty(name)) {
                    Predicate p = builder.like(root.get("name").as(String.class), "%" + name + "%");
                    preds.add(p);
                }

                Predicate p = builder.equal(root.get("bdelete").as(String.class), "0");
                preds.add(p);

                return builder.and(preds.toArray(new Predicate[0]));
            }
        }, pageable);
        page.setData(cePage.getContent());
        page.setTatalPageNum(cePage.getTotalPages());
        page.setTotalNum(cePage.getTotalElements());
        return HttpResult.ok(page);
    }


}
